package com.bigwork.controller;

import com.bigwork.dto.product.ProductDto;
import com.bigwork.entity.Product;
import com.bigwork.service.ProductService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
@Slf4j
public class ProductController {

    private final ProductService productService;

    @PostMapping
    @PreAuthorize("hasAuthority('ROLE_ADMIN')") // Assume only admins can add products
    public ResponseEntity<Product> addProduct(@Valid @RequestBody ProductDto productDto) {
        log.info("API call to add new product: {}", productDto.getName());
        Product newProduct = productService.addProduct(productDto);
        return new ResponseEntity<>(newProduct, HttpStatus.CREATED);
    }

    @GetMapping
    public ResponseEntity<List<Product>> getAllProducts() {
        log.info("API call to get all products");
        List<Product> products = productService.getAllProducts();
        return ResponseEntity.ok(products);
    }

    @GetMapping("/search")
    public ResponseEntity<List<Product>> searchProductsByName(@RequestParam String name) {
        log.info("API call to search products by name: {}", name);
        List<Product> products = productService.searchProductsByName(name);
        return ResponseEntity.ok(products);
    }

    @GetMapping("/category/{category}")
    public ResponseEntity<List<Product>> searchProductsByCategory(@PathVariable String category) {
        log.info("API call to search products by category: {}", category);
        List<Product> products = productService.searchProductsByCategory(category);
        return ResponseEntity.ok(products);
    }
}